import React from 'react'
import NavBar from '@/components/NavBar'
import Input from '@/components/Input'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

export default function Login() {
  const history = useHistory()
  const location = useLocation()
  const [time, setTime] = useState(0)
  const dispatch = useDispatch()
  const onExtraClick = async () => {
    if (time > 0) return
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    await dispatch(sendCode(mobile))
    Toast.success('发送验证码成功', 1)
    setTime(60)
    let timeId = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timeId)
        }
        return time - 1
      })
    }, 1000)
  }
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    onSubmit: async (values) => {
      await dispatch(login(values))
      Toast.success('登录成功')
      if (location.state) {
        history.replace(location.state.from)
      } else {
        history.replace('/home')
      }
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
    // validate: (value) => {
    //   const errors = {}
    //   if (!value.mobile) {
    //     errors.mobile = '手机号不能为空'
    //   }
    //   if (!value.code) {
    //     errors.code = '验证码不能为空'
    //   }
    //   return errors
    // },
  })
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    errors,
    touched,
    handleBlur,
    isValid,
  } = formik
  return (
    //1传递props2.withRouter3.useHistory
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>登录功能</h3>
        <form onSubmit={handleSubmit}>
          <div className="input_item">
            <Input
              name="mobile"
              autoComplete="off"
              placeholder="请输入手机号"
              value={mobile}
              onBlur={handleBlur}
              onChange={handleChange}
              maxLength="11"
            ></Input>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>
          <div className="input_item">
            <Input
              name="code"
              autoComplete="off"
              value={code}
              onExtraClick={onExtraClick}
              extra={time === 0 ? '发送验证码' : `${time}s后重试`}
              placeholder="请输入验证码"
              onBlur={handleBlur}
              onChange={handleChange}
              maxLength="6"
            ></Input>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
